/**
 * 京师书法资源文件解密
 *
 * 需要安装以下依赖:
 * npm install prettier
 */

const fs = require('fs');
const path = require('path');
const prettier = require('prettier');
const toolsNode = require('../libs/tools-node');
const password = 0xFB;

// 获取传递给脚本的参数（排除前两个默认参数）
// 根据文件类型执行解密
const args = process.argv.slice(2);
let from = args[0];
let _ext = path.extname(from).toLowerCase();
let _name = path.basename(from);
_name = _name.replace(/^en_/i, '');
let to = path.join(path.dirname(from), `de_${_name}`);
if (['.mp4', '.wav', '.mp3', '.wma', '.jpg', '.jpeg', '.png', '.gif', '.bmp'].includes(_ext)) {
  decodeFile(10);
} else if (['.txt', '.json', '.xml', '.html', '.css', '.js', '.log'].includes(_ext) || ['base.data', 'disk.disc'].includes(_name)) {
  decodeFile();
} else {
  decodeFile(10);
}

async function formatCodeBuffer(codeBuffer, inputPath) {
  let fileContent = codeBuffer.toString('utf8');
  try {
    // 获取 Prettier 配置（从 .prettierrc 等文件加载）
    let options = await prettier.resolveConfig(inputPath);
    // 格式化代码
    let formattedCode = await prettier.format(fileContent, {
      ...options,
      filepath: inputPath, // 自动推断语言
    });
    return Buffer.from(formattedCode, 'utf8');
  } catch (error) {
    console.error('格式化代码失败:', error);
    // 出错时返回原始Buffer
    return codeBuffer;
  }
}

function decodeFile (len) {
  return new Promise((resolve, reject) => {
    fs.readFile(from, async (err, data) => {
      if (err) {
        reject(`读取文件失败: ${_name}`);
      } else {
        let decrypted = Buffer.from(data);
        let length = len || decrypted.length;
        for (let i = 0; i < length; i++) {
          decrypted[i] = decrypted[i] ^ password;
        }
        if (['base.data', 'disk.disc'].includes(_name) || ['.json', '.xml', '.html', '.css', '.js'].includes(_ext)) {
          let _inputPath = from + (['base.data', 'disk.disc'].includes(_name) ? '.json' : '');
          // 等待格式化完成
          decrypted = await formatCodeBuffer(decrypted, _inputPath);
        }
        toolsNode.writeFileSync(to, decrypted);
        resolve();
      }
    });
  });
};
